import io
import json
from json import JSONDecodeError
import stat
import time
import yaml
import re
from django.conf import settings
from typing import List, Dict, Any

from XApiTestServer.models import ProjectInfo, TestConfig

import traceback

import logging


logger = logging.getLogger('XApiTestServer')

"""
Importor:
1. vue format convert to database format
2. database format convert to vue format
"""


def json_file_to_format(var_type: str, var_value):
    """Convert the JSON file to json format of Python
    :param var_type: str: 类型 (legal var_type: string float int file boolean )
    :return: ok or error ???
    """
    pass

def add_config_data(**kwargs):
    """Add Config Data
    :param kwargs: Config Data
    :return:
    """
    logging.info(kwargs.get('belong_project'))
    try:
        if TestConfig.objects.filter(belong_project=kwargs.get('belong_project'), name=kwargs.get('name')).count() > 0:
            raise Exception('该项目下的配置名称{}已存在'.format(kwargs.get('name')))
        kwargs['belong_project'] = ProjectInfo.objects.get(id=kwargs.get('belong_project'))
        TestConfig.objects.create(**kwargs)
        logging.info('环境配置添加成功: {kwargs}'.format(kwargs=kwargs))
    except Exception as e:
        logging.error('导入失败: {kwargs}'.format(kwargs=kwargs))
        raise Exception('添加配置失败{}'.format(kwargs))

def json_to_config_body(content):
    """Generate TestConfig Info based Json Content
    :param var_type: str: 类型 (legal var_type: string float int file boolean )
    :param var_value: object: 待转换的值
    :return: ok or error ???
    """
    config_content = json.loads(content)
    config_name = config_content.get('name')
    config_variables = config_content.get('values')

    var_item_list = []
    for variable in config_variables:
        var_tmp = {variable["key"]: str(variable["value"])}
        var_item_list.append(var_tmp)

    config_body = {
        'url': {
            'base_url': 'http://json/',
            'auth_url': ''
        },
        'database': [
            {'database_type': 'MySQL'},
            {'database_host': ''},
            {'database_name': ''},
            {'database_user': ''},
            {'database_password': ''},
            {'database_port': 3306}
        ],
        'variables': var_item_list
    }

    return config_name, config_body

def json_to_case(content):
    """Generate TestCase Info based Json
    :param var_type: str: 类型 (legal var_type: string float int file boolean )
    :param var_value: object: 待转换的值
    :return: ok or error ???
    """
    pass
